package com.atguigu.gmalllogger.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guigu.GmallConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ExecutionException;

/**
 * @author wsl
 * @version 2021-01-05
 * GmallLoggerApplication只能扫描同级别或同级别子类的注解，所以Controller位置要注意
 */
@Slf4j

@RestController
public class LoggerController {


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    //http://localhost:8081/log?logString=wsl
    @RequestMapping(value = "log", method = RequestMethod.POST)
    public String getLog(@RequestParam("logString") String logStr) throws ExecutionException, InterruptedException {

        JSONObject jsonObject = JSON.parseObject(logStr);
//        jsonObject.put("ts", System.currentTimeMillis());
//
        String logger = jsonObject.toString();
        log.info(logger);

        SendResult<String, String> result = kafkaTemplate.send(GmallConstant.GMALL_STARTUP, logger).get();
        if (result.getRecordMetadata()!= null) {
            System.out.println(result.getRecordMetadata().toString());
        }


        return "ok";
    }

}
